﻿using System;
using System.Linq;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace FbHelperWP7NonUi.TextHelpers
{
    internal sealed class TextBook : Book
    {
        private const int maxTitleLettersCount = 32;
        private const string longTitleSuffix = "...";

        private static readonly ReadOnlyCollection<Human> authors = new List<Human>().AsReadOnly();

        private TextBook( List<SimpleText> texts )
            : base( texts[0].Text, authors, texts.Cast<AbstractTextPart>().ToList().AsReadOnly() )
        {
        }

        public static TextBook Open( Stream inputStream )
        {
            using (StreamReader streamReader = new StreamReader( inputStream ))
            {
                List<SimpleText> textParts = new List<SimpleText>();

                while (!streamReader.EndOfStream)
                {
                    string newLine = streamReader.ReadLine();

                    if (String.IsNullOrWhiteSpace( newLine ))
                    {
                        textParts.Add( SimpleText.EmptyParagraph );

                        continue;
                    }
                    else
                    {
                        textParts.Add( new SimpleText( newLine ) );
                    }
                }

                if (textParts.Count == 0)
                    textParts.Add( SimpleText.EmptyParagraph );

                return new TextBook( textParts );
            }
        }
    }
}
